package com.wz.base.support.events.publisher;

import com.wz.base.support.events.DomainEventPublisher;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DomainEventsConfig {

    @Bean
    MeterRegistry getMeterRegistry(){
        return new SimpleMeterRegistry();
    }

    /**
     * 异步发布，保存发布日志到数据库
     * @param applicationEventPublisher
     * @param meterRegistry
     * @return
     */
    @Bean(name = "async")
    DomainEventPublisher asyncPublishDomainEventsWithStorage(ApplicationEventPublisher applicationEventPublisher, MeterRegistry meterRegistry) {
        return new StoreAndForwardDomainEventPublisher(
                new MeteredDomainEventPublisher(
                        new JustForwardDomainEventPublisher(applicationEventPublisher), meterRegistry),
                new InMemoryEventsStorage()
        );
    }

    /**
     * 同步发布，不保存发布日志到数据库
     * @param applicationEventPublisher
     * @param meterRegistry
     * @return
     */
    @Bean(name = "sync")
    DomainEventPublisher syncPublishDomainEventsWithOutStorage(ApplicationEventPublisher applicationEventPublisher, MeterRegistry meterRegistry) {
        return new MeteredDomainEventPublisher(new JustForwardDomainEventPublisher(applicationEventPublisher), meterRegistry);
    }

}